import asyncRoutes from '@/router/modules/asyncRoutes';
import { RouteRecordRaw } from 'vue-router';

/**
 * 使用meta.role来确定当前用户是否有权限
 * @param powerList
 * @param route
 */
function hasPermission(powerList: Array<string | number>, route: RouteRecordRaw) {
  if (route.meta && route.meta.id) {
    return powerList.includes(route.meta.id as number)
  } else {
    return true
  }
}

/**
 * 通过递归通过权限过滤异步路由表
 * @param routes asyncRoutes
 * @param powerList
 */
function filterAsyncRoutes(routes: RouteRecordRaw[], powerList: Array<string | number>) {
  const res: RouteRecordRaw[] = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (tmp.children && Array.isArray(tmp.children) && tmp.children.length !== 0) {
      tmp.children = filterAsyncRoutes(tmp.children, powerList)
      if (tmp.children.length > 0) res.push(tmp)
    } else {
      if (hasPermission(powerList, tmp)) {
        res.push(tmp)
      }
    }
  })

  return res
}

export default function(list: Array<string | number | { id?: number, routeId?: number }>) {
  let routeIds: Array<string | number> = []
  if (list.length > 0) {
    if (typeof list[0] === 'number' || typeof list[0] === 'number') {
      routeIds = list as Array<string | number>
    } else if (typeof list[0] === 'object') {
      if (list[0].routeId) {
        routeIds = (list as { routeId: number }[]).map(item => item.routeId)
      } else if (list[0].id) {
        routeIds = (list as { id: number }[]).map(item => item.id)
      } else {
        console.error('用户的权限系统中不存在对应的路由id或者相关key配置错误，请修改代码！ -- DianaYako');
        return []
      }
    }
    let accessedRoutes = filterAsyncRoutes(asyncRoutes, routeIds)
    return accessedRoutes
  } else {
    return []
  }
}